# Post的关键: 
#           1. Header加上 "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8";
#           2. Request加上data参数来接收formdata;

# 模拟在有道进行查单词
from urllib.request import Request
import urllib.request as ur
import urllib.parse as upa

# 通过抓包的方式获取的url，并不是浏览器上显示的url
url_youdao = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null"

# 完整的headers
headers = {
    "Accept" : "application/json, text/javascript, */*; q=0.01",
    "X-Requested-With" : "XMLHttpRequest",
    "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
    "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8",
}


# 发送到web服务器的表单数据
str_to_translate = 'persona'
formdata_dic = {
    "type" : "AUTO",
    "i" : str_to_translate,
    "doctype" : "json",
    "xmlVersion" : "1.8",
    "keyfrom" : "fanyi.web",
    "ue" : "UTF-8",
    "action" : "FY_BY_CLICKBUTTON",
    "typoResult" : "true"
}

# 经过urlencode转码
formdata = upa.urlencode(formdata_dic)
# py3特色: 转成字节流才行
formdata = formdata.encode('utf8')

myreq = Request(url_youdao, data=formdata, headers=headers)

response = ur.urlopen(myreq)

html = response.read().decode('utf8')
print(html)


